package com.wx.frame.controller;

import com.wx.utils.FileUpload;
import com.wx.utils.ServerFileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller("fileUploadController")
@RequestMapping("/file")
public class FileUploadController {
    /*
	 *  图片命名格式
	 */
    private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmss";

    /*
     * 项目绝对路径
     */
    //private static  final String PROJECT_PATH="/Users/myd/Documents/IdeaProjects/wxapp-web/target";
    /*
     * 上传图片文件夹
     */
    private static final String UPLOAD_PATH="/uploadfile/";

    /*
 *  上传图片
 */
    @RequestMapping("uploadImg")
    public void uplodaImg(@RequestParam("upload")MultipartFile file,//
                          HttpServletRequest request, //
                          HttpServletResponse response,//
                          @RequestParam("CKEditorFuncNum")String CKEditorFuncNum)//
            throws IllegalStateException, IOException{
        String PROJECT_PATH ="/wxapp-web";
        PrintWriter out =response.getWriter();
        String fileName=file.getOriginalFilename();
        String uploadContentType =file.getContentType();
        String expandedName ="";
        if (uploadContentType.equals("image/pjpeg")
                || uploadContentType.equals("image/jpeg")) {
            // IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
            expandedName = ".jpg";
        } else if (uploadContentType.equals("image/png")
                || uploadContentType.equals("image/x-png")) {
            // IE6上传的png图片的headimageContentType是"image/x-png"
            expandedName = ".png";
        } else if (uploadContentType.equals("image/gif")) {
            expandedName = ".gif";
        } else if (uploadContentType.equals("image/bmp")) {
            expandedName = ".bmp";
        } else {
            out.println("<script type=\"text/javascript\">");
            out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
                    + ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");
            out.println("</script>");
            return ;
        }
//        if (file.getSize()> 600 * 1024) {
//            out.println("<script type=\"text/javascript\">");
//            out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
//                    + ",''," + "'文件大小不得大于600k');");
//            out.println("</script>");
//            return ;
//        }
        DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
        fileName = df.format(new Date())+expandedName;
        file.transferTo(new File(PROJECT_PATH+UPLOAD_PATH +fileName));
        // 返回"图像"选项卡并显示图片  request.getContextPath()为web项目名
        out.println("<script type=\"text/javascript\">");
        out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
                + ",'" + "/wxapp-web/uploadfile/" + fileName + "','')");
        out.println("</script>");
        return ;
    }



    /**
     * 客户信息导入
     */
    @RequestMapping(value = "/import_img",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String import_img(HttpServletResponse response, HttpServletRequest request, FileUpload file, BindingResult result) {
        if (result.hasErrors()) {   //上传时发生错误
            return "";
        }
        //将文件保存到服务器临时文件夹中
        String fileName = ServerFileUtil.saveFile(request, file.getFile());
        //服务器上文件路径
        //String path = request.getSession().getServletContext().getRealPath("/").replace("//", "/"); //+ File.separator;
//        String fName = path + fileName;
        String fName = "/wxapp-web/"+fileName;

        return  "{success:true,path:'" + fName+ "'}";
    }

}